package com.general.client.widgets.button;

import com.general.client.action.ActionHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.shared.HandlerRegistration;

public class ToggleButton extends AbstractButton implements IToggleButton {

	private boolean isDown = false;

	@Override
	public boolean isDown() {
		return isDown;
	}

	@Override
	public void setDown(boolean down) {
		if (down)
			mainPanel.removeStyleName(common.style().inactive());
		else
			mainPanel.addStyleName(common.style().inactive());
		isDown = down;
	}

	@Override
	protected void init() {
		setUiBinder(getUiBinder());
		initWidget(uiBinder.createAndBindUi(this));
		setDown(false);
		mainPanel.addMouseDownHandler(new MouseDownHandler() {

			@Override
			public void onMouseDown(MouseDownEvent event) {
				if (isEnabled)
					setDown(!isDown);
			}
		});
	}

	@Override
	public HandlerRegistration addActionHandler(final ActionHandler handler) {

		final HandlerRegistration clickHandler = mainPanel.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (isEnabled)
					handler.onAction(event);
			}
		});

		return clickHandler;

	}

}
